package me.eachann.bar;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import me.eachann.library.R;

import static android.util.TypedValue.COMPLEX_UNIT_PX;

/**
 * 自定义简单TitleBar
 */
public final class TitleBar extends LinearLayout {
    private RelativeLayout mMainLayout;
    private TextView mTitleView;
    private View mLineView, mLeftView;
    private View mRightView;
    private boolean fillStatusBar;
    private int mBottomLineHeight;

    public TitleBar(Context context) {
        this(context, null);
    }

    public TitleBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TitleBar, defStyleAttr, 0);
        try {
            fillStatusBar = a.getBoolean(R.styleable.TitleBar_fill_status_bar, true);
        } finally {
            a.recycle();
        }
        setOrientation(VERTICAL);
        initView(context);
        initBar();
        initAttrs(context, attrs, defStyleAttr);
    }

    private void initAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
        final int rightResId;
        boolean isHome;
        boolean showBottomLine;
        String title;
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.TitleBar, defStyleAttr, 0);
        float mTitleTextSize;
        try {
            rightResId = a.getResourceId(R.styleable.TitleBar_right, -1);
            isHome = a.getBoolean(R.styleable.TitleBar_is_home, false);
            showBottomLine = a.getBoolean(R.styleable.TitleBar_show_bottom_line, true);
            if (showBottomLine) {
                mBottomLineHeight = a.getDimensionPixelSize(R.styleable.TitleBar_bottom_line_height, -1);
                setBottomLineHeight();
            }
            mTitleTextSize = a.getDimension(R.styleable.TitleBar_textSize, dp2px(17f));
            title = a.getString(R.styleable.TitleBar_title);
        } finally {
            a.recycle();
        }
        mLeftView.setVisibility(isHome ? GONE : VISIBLE);
        mLineView.setVisibility(!showBottomLine ? GONE : VISIBLE);
        mTitleView.setText(title);
        mTitleView.setTextSize(COMPLEX_UNIT_PX, mTitleTextSize);
        initRightView(rightResId);
    }

    private void initRightView(int rightResId) {
        if (rightResId != -1) {
            mRightView = LayoutInflater.from(getContext()).inflate(rightResId, mMainLayout, false);
            if (mRightView != null) {
                RelativeLayout.LayoutParams endParams = (RelativeLayout.LayoutParams) mRightView.getLayoutParams();
                endParams.addRule(RelativeLayout.ALIGN_PARENT_END, RelativeLayout.TRUE);
                endParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
                endParams.setMarginEnd(dp2px(15f));
//                endParams.bottomMargin = (dp2px(44f) - endParams.height) / 2;
                mRightView.setLayoutParams(endParams);
                mMainLayout.addView(mRightView);
            }
        }
    }

    private void setBottomLineHeight() {
        if (mBottomLineHeight >= 0) {
            mLineView.getLayoutParams().height = mBottomLineHeight;
        }
    }

    private void initView(Context context) {
        mMainLayout = ViewBuilder.newMainLayout(context);
        mLineView = ViewBuilder.newLineView(context);
        mLeftView = ViewBuilder.newLeftView(context);
        mTitleView = ViewBuilder.newTitleView(context);
        mTitleView.setEnabled(false);
        mLeftView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getContext() instanceof Activity) {
                    ((Activity) v.getContext()).finish();
                }
            }
        });
    }

    /**
     * 拦截返回事件，自己处理
     *
     * @param l listener
     */
    public void setOnBackListener(OnClickListener l) {
        if (mLeftView == null) return;
        mLeftView.setOnClickListener(l);
    }


    /**
     * 设置右边布局点击事件
     */
    public void setOnClickRightListener(OnClickListener l) {
        mRightView.setOnClickListener(l);
    }

    private void initBar() {
        mMainLayout.addView(mLeftView);
        mMainLayout.addView(mTitleView);

        if (fillStatusBar) {
            addView(ViewBuilder.newStatusBarView(getContext(), getStatusBarHeight()), 0);
            addView(mMainLayout, 1);
            addView(mLineView, 2);
        } else {
            addView(mMainLayout, 0);
            addView(mLineView, 1);
        }
    }

    public void setTitle(CharSequence title) {
        mTitleView.setText(title);
    }

    public void setTitle(int resId) {
        mTitleView.setText(resId);
    }

    private int mHeight = -1;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 设置 TitleBar 的高度
        switch (MeasureSpec.getMode(heightMeasureSpec)) {
            case MeasureSpec.AT_MOST:
            case MeasureSpec.UNSPECIFIED:
                // 获取 TitleBar 默认高度
                heightMeasureSpec = MeasureSpec.makeMeasureSpec(dp2px(44f), MeasureSpec.EXACTLY);
                break;
            case MeasureSpec.EXACTLY:
            default:
                break;
        }
        if (mHeight == -1) {
            mHeight = getSize(heightMeasureSpec) + (fillStatusBar ? getStatusBarHeight() : 0);
        }

        heightMeasureSpec = MeasureSpec.makeMeasureSpec(mHeight, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        setMeasuredDimension(getContext().getResources().getDisplayMetrics().widthPixels, getSize(heightMeasureSpec) + (fillStatusBar ? getStatusBarHeight() : 0));

    }

    private int getSize(int heightMeasureSpec) {
        int result;
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        switch (specMode) {
            case MeasureSpec.EXACTLY://match_parent or 确切大小40dp
                result = specSize;//确切大小,所以将得到的尺寸给view
                break;
            case MeasureSpec.AT_MOST://wrap_content
                //默认值为450px,此处要结合父控件给子控件的最多大小(要不然会填充父控件),所以采用最小值
                result = Math.min(dp2px(44f), specSize);
                break;
            case MeasureSpec.UNSPECIFIED://未指定
            default:
                result = dp2px(44f);
                break;
        }
        return result;
    }

    /**
     * convert dp to its equivalent px
     * <p>
     * 将dp转换为与之相等的px
     */
    private int dp2px(float dipValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private int getStatusBarHeight() {
        int height = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = getResources().getDimensionPixelSize(resourceId);
        }
        return height;
    }

    /**
     * 获取右侧view
     *
     * @return mRightView
     */
    public View getRightView() {
        return mRightView;
    }

}
